/**
 * 该文件为路由接口（添加、删除、修改、查询各类lp信息）
 */

const express=require("express");
const router=express.Router();
const path=require("path");
const fs=require("fs");

// 引入数据库model
const {WifeModel,RoleWifeModel}=require("../../models/Wifes.js");

// 引入passport模块
const passport=require("passport");

//引入全局输出类
const JsonResult=require("../global/JsonResult.js");

// 引入图片上传路径模块
// const upload=require("../../middleware/upload.js");
const upload=require("../../middleware/uploadMultipleImage.js");
const multer=require("multer");

// 引入查询条件和配置项
const UnityParams=require("../conditions/unityParams.js");

// 添加lp接口--（/api/wifes/add）
router.post("/add",passport.authenticate("jwt",{session:false}),(req,res,next)=>{
    upload.array("images",6)(req,res,async (err)=>{
        // console.log(req.body,req.file,req.files,err);
        if(err instanceof multer.MulterError){
            // console.log(err.message);
            if(err.message === "File too large"){
                res.json(JsonResult.middlewareFail("图片大小不得超过20M",null));
            }else{
                res.json(JsonResult.middlewareFail("发生错误",null));
            };
        }else if(err){
            res.json(JsonResult.middlewareFail(err.message,null));
        }else{
            // console.log(req.body,req.files);
            // WifeModel.find().populate("userId").then((doc)=>{
            //     console.log(doc);
            // });
            // 若未选角色，则默认给其赋值20（其他）角色关系
            req.body.role=req.body.role?req.body.role:"20";
            let role=req.body.role.split(",").map((item)=>{
                return RoleWifeModel.findOne({roleType:item}).then((doc)=>{
                    return doc._id;
                });
            });
            let p = await Promise.all(role).then((res)=>{
                return res;
            });
            const wife=new WifeModel({
                name:req.body.name,
                age:req.body.age,
                role:p,
                detail:req.body.detail,
                images:req.files.length !=0 ? req.files.map((item)=>{
                    return {
                        fileName:item.filename,
                        size:item.size
                    };
                }) : null,
                date:req.body.date,
                userId:req.body.userId
            });
            wife.save().then((doc)=>{
                // console.log("添加的用户图片信息",doc);
                res.json(JsonResult.success("添加信息成功",null));
            }).catch((error)=>{
                // console.log(error.message);
                if(error.message.includes("duplicate key")){
                    res.status(500).json(JsonResult.databaseError("姓名不能重复",null));
                }else{
                    res.status(500).json(JsonResult.databaseError("数据库添加信息出错",null));
                };
            });
        };
    });
});

// 编辑lp接口--（/api/wifes/edit/:id）
router.post("/edit/:id",passport.authenticate("jwt",{session:false}),(req,res,next)=>{
    upload.array("images",6)(req,res,async (err)=>{
        // console.log(req.body,req.params,req.files);
        if(err instanceof multer.MulterError){
            // console.log(err.message);
            if(err.message === "File too large"){
                res.json(JsonResult.middlewareFail("图片大小不得超过20M",null));
            }else{
                res.json(JsonResult.middlewareFail("发生错误",null));
            };
        }else if(err){
            res.json(JsonResult.middlewareFail(err.message,null));
        }else{
            req.body.role=req.body.role?req.body.role:"20";
            let role=req.body.role.split(",").map((item)=>{
                return RoleWifeModel.findOne({roleType:item}).then((doc)=>{
                    return doc._id;
                });
            });
            let p = await Promise.all(role).then((res)=>{
                return res;
            });
            // 表示编辑时上传了图片
            if(req.files && req.files.length>0){
                if(req.body.oldImages){ //表示编辑时既有未修改的图片也有新上传的图片
                    WifeModel.findByIdAndUpdate(req.params.id,{
                        $set:{
                            name:req.body.name,
                            age:req.body.age,
                            role:p,
                            detail:req.body.detail,
                            date:req.body.date,
                            userId:req.body.userId,
                            updateTime:Date.now(),
                            images:req.files.map((item)=>{
                                return {
                                    fileName:item.filename,
                                    size:item.size
                                };
                            }).concat(typeof req.body.oldImages === "string" ? 
                                [{fileName:req.body.oldImages}] :
                                req.body.oldImages.map((item)=>{
                                    return {
                                        fileName:item
                                    };
                                })
                            )
                        }
                    },{
                        new:false
                    }).then((doc)=>{
                        // console.log(doc);
                        doc.images.forEach((item)=>{
                            if(typeof req.body.oldImages === "string"){
                                if(item.fileName !== req.body.oldImages){
                                    fs.unlink(path.resolve(__dirname,"../../public/uploads/wifes/",item.fileName),(err,buffer)=>{
                                        if(!err){
                                            console.log("文件删除成功");
                                        };
                                    });
                                };
                            }else{
                                if(!req.body.oldImages.includes(item.fileName)){
                                    fs.unlink(path.resolve(__dirname,"../../public/uploads/wifes/",item.fileName),(err,buffer)=>{
                                        if(!err){
                                            console.log("文件删除成功");
                                        };
                                    });
                                };
                            };
                        });
                        res.json(JsonResult.success("修改成功",null));
                    }).catch((err)=>{
                        res.status(500).json(JsonResult.databaseError("数据库修改出错",null));
                    });
                }else{ //表示编辑时只有新上传的图片
                    WifeModel.findByIdAndUpdate(req.params.id,{
                        $set:{
                            name:req.body.name,
                            age:req.body.age,
                            role:p,
                            detail:req.body.detail,
                            date:req.body.date,
                            userId:req.body.userId,
                            updateTime:Date.now(),
                            images:req.files.map((item)=>{
                                return {
                                    fileName:item.filename,
                                    size:item.size
                                };
                            })
                        }
                    },{
                        new:false
                    }).then((doc)=>{
                        // console.log(doc);
                        doc.images.forEach((item)=>{
                            fs.unlink(path.resolve(__dirname,"../../public/uploads/wifes/",item.fileName),(err,buffer)=>{
                                if(!err){
                                    console.log("文件删除成功");
                                };
                            });
                        });
                        res.json(JsonResult.success("修改成功",null));
                    }).catch((err)=>{
                        res.status(500).json(JsonResult.databaseError("数据库修改出错",null));
                    });
                };
            }else{ //表示编辑时未上传图片
                WifeModel.findByIdAndUpdate(req.params.id,{
                    $set:{
                        name:req.body.name,
                        age:req.body.age,
                        role:p,
                        detail:req.body.detail,
                        date:req.body.date,
                        userId:req.body.userId,
                        updateTime:Date.now(),
                        images:req.body.oldImages ? 
                            typeof req.body.oldImages === "string" ? 
                            [{fileName:req.body.oldImages}] :
                            req.body.oldImages.map((item)=>{
                                return {
                                    fileName:item
                                };
                            }) : null//判断未编辑的图片是单张还是多张
                    }
                },{
                    new:false
                }).then((doc)=>{
                    // console.log(doc);
                    doc.images.forEach((item)=>{
                        if(typeof req.body.oldImages === "string"){
                            if(item.fileName !== req.body.oldImages){
                                fs.unlink(path.resolve(__dirname,"../../public/uploads/wifes/",item.fileName),(err,buffer)=>{
                                    if(!err){
                                        console.log("文件删除成功");
                                    };
                                });
                            };
                        }else{
                            if(!req.body.oldImages.includes(item.fileName)){
                                fs.unlink(path.resolve(__dirname,"../../public/uploads/wifes/",item.fileName),(err,buffer)=>{
                                    if(!err){
                                        console.log("文件删除成功");
                                    };
                                });
                            };
                        };
                    });
                    res.json(JsonResult.success("修改成功",null));
                }).catch((err)=>{
                    res.status(500).json(JsonResult.databaseError("数据库修改出错",null));
                });
            };
        };
    });
});

// 删除lp接口--（/api/wifes/delete/:id）
router.delete("/delete/:id",passport.authenticate("jwt",{session:false}),(req,res,next)=>{
    WifeModel.findByIdAndDelete(req.params.id).then((doc)=>{
        // console.log(doc);
        doc.images.forEach((item)=>{
            fs.unlink(path.resolve(__dirname,"../../public/uploads/wifes/",item.fileName),(err,buffer)=>{
                if(!err){
                    console.log("文件删除成功");
                };
            });
        });
        res.json(JsonResult.success("删除成功",null));
    }).catch((err)=>{
        res.status(500).json(JsonResult.databaseError("数据库删除出错",null));
    });
});

// 查看lp接口--（/api/wifes）
router.get("/",passport.authenticate("jwt",{session:false}),async (req,res,next)=>{
    let counts=UnityParams.counts;
    let unityDataObj=UnityParams.unityDataObj(req.query);
    let unityOptionsObj=UnityParams.unityOptionsObj(req.query);
    // await WifeModel.countDocuments().then((count)=>{
    //     counts=count;
    // }).catch((err)=>{
    //     // console.log(err);
    //     res.status(500).json(JsonResult.databaseError("数据库操作出错",null));
    // });
    counts=await WifeModel.countDocuments();
    WifeModel.find(unityDataObj,null,unityOptionsObj)
        // .populate("userId",{name:true,email:true})
        .populate("userId","name email")
        // .populate({path:"userId",select:"name email",match:{name:"qilin"},options:{sort:{name:-1}}})
        .populate({path:"role"})
        .then((doc)=>{
            res.json(JsonResult.success("查询成功",{
                currentPage:req.query.pageNum?req.query.pageNum:1,
                currentSize:req.query.pageSize?req.query.pageSize:5,
                total:counts,
                data:doc
        }));
    }).catch((err)=>{
        console.log(err);
        res.status(500).json(JsonResult.databaseError("查询lp信息出错",null));
    })
});

// 添加lp角色接口--（/api/wifes/addRoleWife）--可直接向数据库导入数据
router.post("/addRoleWife",passport.authenticate("jwt",{session:false}),(req,res,next)=>{
    const roleWife=new RoleWifeModel({
        roleType:req.body.roleType,
        roleName:req.body.roleName
    });
    roleWife.save().then((doc)=>{
        // console.log("添加的角色信息",doc);
        res.json(JsonResult.success("添加角色信息成功",null));
    }).catch((err)=>{
        // console.log(err);
        res.status(500).json(JsonResult.databaseError("数据库添加角色信息出错",null));
    });
});

// 查询lp角色接口--（/api/wifes/viewRoleWife）
router.get("/viewRoleWife",passport.authenticate("jwt",{session:false}),async (req,res,next)=>{
    let counts=UnityParams.counts;
    let unityDataObj=UnityParams.unityDataObj(req.query);
    let unityOptionsObj=UnityParams.unityOptionsObj({...req.query,sort:{roleType:1}});
    // await RoleWifeModel.countDocuments().then((count)=>{
    //     counts=count;
    // }).catch((err)=>{
    //     // console.log(err);
    //     res.status(500).json(JsonResult.databaseError("数据库操作出错",null));
    // });
    counts=await RoleWifeModel.countDocuments();
    RoleWifeModel.find(unityDataObj,null,unityOptionsObj).then((doc)=>{
        res.json(JsonResult.success("查询成功",{
            currentPage:req.query.pageNum?+req.query.pageNum:1,
            currentSize:req.query.pageSize?+req.query.pageSize:5,
            total:counts,
            data:doc
        }));
    }).catch((err)=>{
        // console.log(err);
        res.status(500).json(JsonResult.databaseError("查询lp角色信息出错",null));
    })
});

module.exports=router;